package handlers

import (
	"ota-backend/storage"

	"github.com/gin-gonic/gin"
)

// SetupRoutes 设置路由
func SetupRoutes(r *gin.Engine, storage *storage.LocalStorage, contentPath string) {
	// 创建处理器
	productHandler := NewProductHandler()
	firmwareHandler := NewFirmwareHandler(storage)
	taskHandler := NewTaskHandler()
	deviceHandler := NewDeviceHandler()
	otaHandler := NewOTAHandler(storage)
	authHandler := NewAuthHandler()
	bfpHandler := NewBruteForceProtection()

	// 构建完整路径
	otaPath := contentPath + "/ota"
	apiPath := contentPath + "/api"

	// 如果contentPath是根路径，则不添加前缀
	if contentPath == "/" {
		otaPath = "/ota"
		apiPath = "/api"
	}

	// OTA服务（需要JWT认证）
	ota := r.Group(otaPath)
	ota.Use(OTAAuthMiddleware()) // 应用OTA JWT认证中间件
	{
		ota.POST("/check", otaHandler.CheckUpdate)
		ota.GET("/download/:product_id/:filename", firmwareHandler.DownloadFirmware)
		ota.POST("/report", otaHandler.ReportUpgradeStatus)
	}

	// API路由组（需要认证）
	api := r.Group(apiPath)
	api.Use(AuthMiddleware()) // 应用认证中间件
	{
		// 认证相关接口
		auth := api.Group("/auth")
		{
			auth.POST("/login", authHandler.Login)
		}

		// 安全管理
		security := api.Group("/security")
		{
			security.GET("/blocked-ips", bfpHandler.GetBlockedIPs)
			security.DELETE("/blocked-ips/:ip", bfpHandler.UnblockIP)
			security.GET("/login-failures", bfpHandler.GetLoginFailures)
			security.DELETE("/login-failures", bfpHandler.ClearLoginFailures)
		}

		// 产品管理
		products := api.Group("/products")
		{
			products.POST("", productHandler.CreateProduct)
			products.GET("", productHandler.GetProducts)
			products.GET("/:id", productHandler.GetProduct)
			products.PUT("/:id", productHandler.UpdateProduct)
			products.DELETE("/:id", productHandler.DeleteProduct)
		}

		//fmt.Sprintf("registers:%s\n", "routes")

		// 固件管理
		firmwares := api.Group("/firmwares")
		{
			firmwares.POST("", firmwareHandler.CreateFirmware)
			firmwares.GET("", firmwareHandler.GetFirmwares)
			firmwares.GET("/:id", firmwareHandler.GetFirmware)
			firmwares.DELETE("/:id", firmwareHandler.DeleteFirmware)
			firmwares.GET("/download/:filename", firmwareHandler.DownloadFirmware)
		}

		// 任务管理
		tasks := api.Group("/tasks")
		{
			tasks.POST("", taskHandler.CreateTask)
			tasks.GET("", taskHandler.GetTasks)
			tasks.GET("/:id", taskHandler.GetTask)
			tasks.PUT("/:id", taskHandler.UpdateTask)
			tasks.DELETE("/:id", taskHandler.DeleteTask)
		}

		// 设备管理
		devices := api.Group("/devices")
		{
			devices.POST("", deviceHandler.CreateDevice)
			devices.GET("", deviceHandler.GetDevices)
			devices.GET("/:id", deviceHandler.GetDevice)
			devices.PUT("/:id", deviceHandler.UpdateDevice)
			devices.DELETE("/:id", deviceHandler.DeleteDevice)
			devices.PUT("/status/:sn", deviceHandler.UpdateDeviceStatus)
			devices.GET("/query", deviceHandler.DeviceQuery)
		}

		// 升级记录
		upgradeRecords := api.Group("/upgrade-records")
		{
			upgradeRecords.GET("", otaHandler.GetUpgradeRecords)
		}
	}
}
